/**
 * 
 */
package edu.gtcfla.km.platform.service.impl;

import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.vsg.biz.account.Menu;
import org.vsg.biz.account.repositories.MenuRepo;
import org.vsg.security.DefaultResourceslPermission;
import org.vsg.security.ResourcesPermission;
import org.vsg.security.ResourcesPermissionException;

import edu.gtcfla.km.platform.service.ShiroMenuPermissionRuleManager;
import edu.gtcfla.km.platform.vo.MenuPermissionVO;

/**
 * @author vison
 *
 */
public class MenuShiroPermissionRuleManager implements ShiroMenuPermissionRuleManager {
	

	@Autowired(required=false)
	private MenuRepo menuRepo;

	

	/* (non-Javadoc)
	 * @see org.vsg.security.strategy.ShiroPermissionRuleManager#process()
	 */
	@Override
	public Set<MenuPermissionVO> process(Subject subject) {
		// TODO Auto-generated method stub
		Set<MenuPermissionVO> menuPerms = new LinkedHashSet<MenuPermissionVO>();
		
		// --- find all menu entity form persistance and covert permission ---
		Iterable<Menu> allAvailableMenu = menuRepo.findAvailable();
		
		
		for (Menu menu : allAvailableMenu) {
			// --- contruct new menu permission ---
			String resId = ResourcesPermission.Helper.parseResourceId( menu.getId() );
			try {
				DefaultResourceslPermission accessDrp = new DefaultResourceslPermission("mnu:access,view:"+resId);
				DefaultResourceslPermission denyDrp = new DefaultResourceslPermission("mnu:deny:"+resId);
				
				MenuPermissionVO menuPerm = new MenuPermissionVO();
				if ( subject.isPermitted(accessDrp) ) {
					// --- add menu contontent ---

					menuPerm.setId( menu.getId() );
					menuPerm.setAcl("access");
				} else if (subject.isPermitted(denyDrp))  {
					menuPerm.setId( menu.getId() );
					menuPerm.setAcl("deny");
				} else {
					menuPerm.setId( menu.getId() );
					menuPerm.setAcl("deny");
					
				}
				menuPerms.add( menuPerm );
				
			} catch (ResourcesPermissionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			
		}
	

		return menuPerms;
	}


}
